package com.siblings.loan.ui.user.impl

import android.content.Context
import com.siblings.loan.http.IHttpCallback
import com.siblings.loan.ui.user.view.ISibLoginView
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.loan.utils.helper.SibAnalysisHelper
import com.siblings.loan.utils.helper.TestAnalysisAddEvent
import com.siblings.mvp.presenter.MvpPresenter
import org.json.JSONObject

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/6/14 16:26
 * @Annotation：用户登录 Presenter 实现
 */
class SibLoginPresenterImpl(context: Context?) : MvpPresenter<ISibLoginView>(context) {
    private var loginModel: SibLoginModelImpl? = null

    init {
        loginModel = SibLoginModelImpl()
    }

    /**
     * 发送验证码
     */
    fun sendSibSmsCodeAction(){
        //发送验证码之前，需要验证手机号是否在 app配置 accListV2里存在
        val commonData = JSONObject(SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON))
        val customize = commonData.optJSONObject("customize")
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accListV2")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (mvpView.getSibMobile() == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            onSibLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        loginModel!!.sendSibSmsCodeAction(mvpView.getSibMobile(),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//发送成功
                        val obj = data.optJSONObject("obj")
                        //是否直接登录
                        val directLoginFlag = obj?.optString("directLoginFlag", "NO")
                        if (directLoginFlag == "YES"){
                            //直接执行登录接口  code: 0000
                            loginSibAction(mvpView!!.getSibMobile(),"0000",directLoginFlag)
                            return
                        }
                        mvpView!!.showSenCodeSuccess()
                    }
                    else -> {
                        mvpView.showSibToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 登录
     */
    fun loginSibAction(mobile: String,code: String,directLoginFlag: String){
        loginModel!!.loginSibAction(mobile,code,directLoginFlag,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//登录成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            val userId = obj.optString("userId")
                            val userToken = obj.optString("token")
                            val type = obj.optString("type")

                            //是否是渠道用户
                            val isAdSource = obj.optString("isAdSource")
                            if ("YES" == isAdSource){
                                SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_IS_ADSOURCE,true)
                            }

                            //登录类型 == 注册，需要打点
                            if (type == "REGISTER"){
                                TestAnalysisAddEvent.addRegisterEvent()
                            }
                            onSibLoginSuccess(userId,userToken)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView!!.showSibToast(msg)
                        mvpView!!.showSibLoginFailure(data)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 登录成功
     */
    private fun onSibLoginSuccess(uid: String, token: String){
        mvpView!!.hideSibLoading()
        //保存手机号码，个人中心使用
        SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_MOBILE, mvpView.getSibMobile())
        //保存用户登录状态为已登录
        SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_LOGIN,true)
        //保存用户id
        SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_USERID,uid)
        //保存用户Token
        SharedHelper.saveSibSPData(SharedHelper.SIB_SPKEY.SIBLINGS_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        SibAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入欢迎页面
        mvpView!!.showSibMainPage()
    }

    /**
     * 获取默认额度
     */
    fun getAmount(): String {
        var homeAmount = "300000"
        val data = JSONObject(SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON))
        val customizeObj = data.optJSONObject("customize")
        if (customizeObj != null) {
            homeAmount = customizeObj.optString("homeAmount", "300000")
        }
        return homeAmount
    }
}